<template>
  <div class="custList">
    <el-form>
      <el-form-item label="标签分类">
        <el-col :span="22">
          <tag-select ref="tagSelect" :tagClass="tagClass" @change="handleSelect"></tag-select>
        </el-col>
        <el-col :span="22" class="m-select" v-if="selectLabelV">
          <p>标签名</p>
          <el-select v-model="selectLabelModel" placeholder="请选择标签" @change="handleSelectLabel">
            <el-option v-for="item in selectLabelOption"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-col>
      </el-form-item>
    </el-form>
    <el-row>
     <el-col :span="8">
        <el-input v-model="searchForm.key" placeholder="手机号、邮箱" @keyup.enter.native="submitSearch">
          <el-button type="primary" slot="append" @click="submitSearch">搜索</el-button>
        </el-input>
      </el-col>
    </el-row>
    <el-row class="mrt">
      <el-button type="button" @click="dialogVisible1 = true" :disabled="!!group">保存为动态群组</el-button>
      <el-dropdown trigger="click" @command="handleAddStatic">
        <el-button type="button">
          保存为静态群组<i class="el-icon-caret-bottom el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown" style="width:140px">
          <el-dropdown-item command="1">保存筛选结果</el-dropdown-item>
          <el-dropdown-item command="2">保存勾选选项</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-dropdown trigger="click" @command="handleAddTag">
        <el-button type="button">
          添加标签<i class="el-icon-caret-bottom el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="1">为筛选结果添加</el-dropdown-item>
          <el-dropdown-item command="2">为勾选选项添加</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
        <el-upload
          class="upload-wrap"
          ref="upload"
          :headers="headers"
          :action="baseUrl+'/customer/buyer/excel/import'"
          :on-remove="handleRemove"
          :on-success="handleImport"
          :auto-upload="true">
          <el-button @click="submitUpload">导入意向客户</el-button>
        </el-upload>
        <a :href="baseUrl+'/customer/buyer/excel/template'" download class="btn-primary">下载导入模板</a>
    </el-row>
    <div class="table-wrap">
      <el-table v-loading="tbLoading" element-loading-text="拼命加载中" :data="custList.list" stripe class="table" @selection-change="handleSelectionChange" @selection="handleSelectItem">
        <template slot-scope="props">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="手机号" className="is-center">
            <template slot-scope="scope">
             {{scope.row.mobile}}
            </template>
          </el-table-column>
          <el-table-column label="邮箱" className="is-center">
            <template slot-scope="scope">
              <a :href="'mailTo:'+scope.row.email">{{scope.row.email}}</a>
            </template>
          </el-table-column>
          <el-table-column label="会员账号" className="is-center">
            <template slot-scope="scope">
             {{scope.row.ssoid}}
            </template>
          </el-table-column>
          <el-table-column label="标签" className="is-center">
            <template slot-scope="scope">
              {{customerTagsString(scope.row.tags)}}
              <!-- <el-tag v-for="tag in scope.row.tags" :key="tag.name" closable @close="handleCloseTag(scope, tag)" style="margin-right: 10px">{{tag.name}}</el-tag> -->
            </template>
          </el-table-column>
          <el-table-column label="营销次数" className="is-center">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.smsTimes === 0 && scope.row.emailTimes > 0" :content=" '邮件' + scope.row.emailTimes" placement="right-end">
                <el-button type="text" @click="handleOpenDialog(scope)">{{scope.row.emailTimes}}</el-button>
              </el-tooltip>
              <el-tooltip v-else-if="scope.row.emailTimes === 0 && scope.row.smsTimes > 0" :content="'短信' + scope.row.smsTimes" placement="right-end">
                <el-button type="text" @click="handleOpenDialog(scope)">{{scope.row.smsTimes + scope.row.emailTimes}}</el-button>
              </el-tooltip>
              <p v-else-if="scope.row.smsTimes + scope.row.emailTimes === 0 ">暂无营销</p>
              <el-tooltip v-else :content="'短信' + scope.row.smsTimes + ', 邮件' + scope.row.emailTimes" placement="right-end">
                <el-button type="text" @click="handleOpenDialog(scope)">{{scope.row.smsTimes + scope.row.emailTimes}}</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="最近导入时间" className="is-center">
            <template slot-scope="scope">
              <!-- {{new Date(scope.row.createTime).toLocaleString()}} -->
              {{$date.format(scope.row.createTime, 'YYYY-MM-DD HH:mm:ss')}}
            </template>
          </el-table-column>
        </template>
      </el-table>
    </div>
    <!-- 主分页 -->
    <div class="pagination">
      <el-pagination
        :current-page.sync="searchForm.page"
        :page-size.sync="searchForm.size"
        layout="total, sizes, prev, pager, next"
        :page-sizes="[10, 30, 50, 100]"
        :total= "custList.page.total"
        @current-change="submitSearch"
        @size-change="handleSizeChange">
      </el-pagination>
    </div>
    <!-- 保存为动态群组弹层 -->
    <el-dialog title="保存为动态群组" :visible.sync="dialogVisible1" width="30%">
      <el-form label-width="70px">
        <el-form-item label="群组名称">
          <el-input v-model="smartGroup"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="handleSaveAsSmart" :loading="isSaving">保存</el-button>
      </div>
    </el-dialog>
    <!-- 添加标签弹层 -->
    <el-dialog title="添加标签" :visible.sync="dialogVisible2" width="30%">
      <el-form label-width="70px">
        <el-form-item label="标签名称">
          <el-select v-model="tagID" remote filterable clearable :remote-method="queryTagAsync" :loading="groupLoading" placeholder="请输入标签关键词" style="width:100%">
            <el-option v-for="item,n in tagList.list" :value="item.id" :label="item.name + ' （分类：' + item.pname + '）'" :key="n.toString()"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false">取 消</el-button>
        <el-button type="primary" :loading="isSaving" @click="handleSaveTag">保存</el-button>
      </div>
    </el-dialog>
    <!-- 保存为静态群组弹层 -->
    <el-dialog title="保存静态群组" :visible.sync="dialogVisible3" width="30%">
      <el-form label-width="120px">
        <el-form-item label="1">
          <el-input v-model="staticGroup"></el-input>
          <div slot="label"><el-radio v-model="ifNewStatic" :label="true">新建静态群组</el-radio></div>
        </el-form-item>
        <el-form-item label="1">
          <el-select v-model="staticGroup2" remote filterable clearable :remote-method="handleSearchGroup" :loading="groupLoading" placeholder="请输入群组关键词" style="width:100%">
            <el-option v-for="item,n in groupList.list" :value="item.id" :label="item.name" :key="n.toString()"></el-option>
          </el-select>
          <div slot="label"><el-radio v-model="ifNewStatic" :label="false">加入已有群组</el-radio></div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible3 = false">取 消</el-button>
        <el-button type="primary" @click="ifNewStatic?handleSaveAsNewStatic():handleSaveAsExistStatic()" :loading="isSaving">保存</el-button>
      </div>
    </el-dialog>
    <!-- 营销次数弹出层 -->
    <el-dialog
      title="营销次数"
      :visible.sync="dialogVisible4"
      width="50%">
        <el-table :data="broadData.list" border style="width: 100%" height="441" @sort-change="handleSortChange">
          <el-table-column className="is-center" label="营销标题">
            <template slot-scope="scope">{{scope.row.title || '营销标题'}}</template>
          </el-table-column>
          <el-table-column className="is-center" label="营销时间">
            <template slot-scope="scope">
              <!-- {{ new Date(scope.row.createTime).toLocaleString() }} -->
              {{$date.format(scope.row.createTime, 'YYYY-MM-DD HH:mm:ss')}}
            </template>
          </el-table-column>
          <el-table-column className="is-center" label="营销类型">
            <template slot-scope="scope">{{scope.row.type === 3 ? '短信' : '邮件'}}</template>
          </el-table-column>
        </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible4 = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible4 = false">确 定</el-button>
      </span>
      <!-- 弹框分页 -->
      <div class="pagination">
        <el-pagination
          :current-page.sync="dialogPage"
          :page-size.sync="dialogSize"
          layout="total, sizes, prev, pager, next"
          :page-sizes="[10, 30, 50, 100]"
          :total= "broadData.page.total"
          @current-change="handleSearchCount"
          @size-change="handleDialogSizeChange">
        </el-pagination>
      </div>
    </el-dialog>
    <!-- 导入excel数据弹窗 -->
    <el-dialog
      title="导入结果"
      width="30%"
      :visible.sync="importResVis"
      class="import-result"
    >
      <span class="sp">成功：{{importSuccess}}个<br />失败：{{importFail}}个</span>
      <!-- <el-button type="text" @click="loadFailData">下载模板</el-button> -->
      <a v-if="importFail" :href="baseUrl+'/customer/buyer/excel/error-list?key=' + importFailKey" download class="btn-primary">下载失败列表</a>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importResVis = false">取 消</el-button>
        <el-button type="primary" @click="importResVis = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {mapState, mapActions} from 'vuex'
  import tagTree from '@/components/common/cusManage/tagTree'
  import tagSelect from '@/components/common/cusManage/tagSelect'
  import env from '@/config/env'
  export default {
    data () {
      return {
        searchForm: {
          key: '',
          page: 1,
          size: 10
        },
        dialogPage: 1,
        dialogSize: 10,
        dialogTotal: 0,
        tbLoading: false,
        isSaving: false,
        group: null,
        groupLoading: false,
        dialogVisible1: false,
        dialogVisible2: false,
        dialogVisible3: false,
        dialogVisible4: false,
        importResVis: false,
        importSuccess: 0,
        importFail: 0,
        importFailKey: '',
        smartGroup: '',
        staticGroup: '',
        staticGroup2: '',
        selections: [],
        tagID: '',
        ifNewStatic: true,
        multipleSelection: [],
        baseUrl: env.baseUrl,
        dialogData: {},
        selectLabelOption: [],
        selectLabelModel: '',
        selectLabelV: false,
        labelId: 0,
        selCondition: '',
        broadData: {
          page: {
            total: 0
          }
        }
      }
    },
    components: {tagTree, tagSelect},
    computed: {
      ...mapState({
        tagList: state => state.cusManage.tagList,
        custList: state => state.cusManage.intCustList,
        conditionsObj: state => state.cusManage.conditionsObj,
        intConditionsObj: state => state.cusManage.intConditionsObj,
        groupList: state => state.cusManage.groupList,
        tagClass: state => state.cusManage.tagClass,
        groupId: state => state.userInfo.groupId
      }),
      conditions () {
        let relationType = this.conditionsObj.relationType
        let conditionsGroup = this.conditionsObj.conditionsGroup
        return {relationType, conditionsGroup}
      },
      // 文件上传附加的头部
      headers () {
        return {
          UBToken: localStorage.getItem('UBToken')
        }
      }
    },
    mounted () {
      this.getPageData(this.groupId)
    },
    methods: {
      ...mapActions(['searchTags', 'getCustomerTags', 'getChildTagClass', 'getExcTemp', 'importFile', 'getCustomerList', 'createDynamicGroup2', 'createStaticGroup1', 'createStaticGroup2', 'createStaticGroup3', 'getCusGroups2', 'addCusTagByID', 'addCusTagByCondition', 'getSaleRecord', 'addToStaticGroup3']),
      // 初始化页面数据
      getPageData (gid) {
        this.searchTags({gid})
          .then(res => {
            if (res.data.code === 1) {
              this.tbLoading = false
            }
          })
        this.getChildTagClass({gid: gid}).then((res) => {
        })
        if (!this.$route.params.gid) {
          this.getCustomerList({ page: this.searchForm.page, size: this.searchForm.size, key: this.searchForm.key })
        } else {
          this.getCustomerList({ page: this.searchForm.page, size: this.searchForm.size, key: this.searchForm.key, groupId: this.$route.params.gid })
        }
        if (this.$route.params.staticGroup2) {
          this.ifNewStatic = false
          this.staticGroup2 = this.$route.params.staticGroup2
        }
      },
      // 选择标签分类
      handleSelect (pid, index) {
        this.selectLabelOption = []
        this.selectLabelModel = ''
        function TagObj (id, name) {
          this.id = id
          this.name = name
        }
        if (pid) {
          this.selCondition = pid
          this.getChildTagClass({index: index, pid: pid, gid: this.groupId}).then((res) => {
            // console.log(res.data.data.length)
            this.searchTags({ pid: pid }).then((res) => {
              /* console.log(res.data.data.list) */
              if (res.data.data.list === undefined || res.data.data.list.length === 0) {
                this.selectLabelV = false
              } else {
                this.selectLabelV = true
              }
              res.data.data.list.map(item => {
                let tagOption = new TagObj(item.id, item.name)
                this.selectLabelOption.push(tagOption)
              })
            })
          })
        }
      },
      handleSelectLabel (labelId) {
        this.tbLoading = true
        this.labelId = labelId
        this.getCustomerList({ page: this.searchForm.page, size: this.searchForm.size, labelId: labelId }).then((res) => {
          if (res.data.code === 1) {
            this.tbLoading = false
          } else {
            this.$message({
              type: 'info',
              message: res.msgZ
            })
          }
        })
      },
      handleSelectionChange (selection) {
        this.selections = selection
        // this.multipleSelection = selection
      },
      handleSelectItem (selection, row) {
        this.selections = selection
      },
      submitSearch () {
        this.tbLoading = true
        this.getCustomerList({ page: this.searchForm.page, size: this.searchForm.size, key: this.searchForm.key })
          .finally((res) => { this.tbLoading = false })
      },
      handleRemove (file) {
        // console.log(file)
      },
      submitUpload () {
        // this.$refs.upload.submit()
      },
      handleImport (response, file) {
        if (response.code === 1) {
          this.importSuccess = response.data.success
          this.importFail = response.data.fail
          this.importFailKey = response.data.errorList
          this.importResVis = true
          this.$message({
            type: 'success',
            message: response.msgZ
          })
        } else {
          this.$message({
            type: 'info',
            message: response.msgZ
          })
        }
        this.getCustomerList({ ...this.searchForm }).then((res) => {
          console.log(res.data)
        })
      },
      loadFailData () {
        console.log('下载')
      },
      // 改变分页大小
      handleSizeChange (size) {
        this.searchForm.size = size
        this.getCustomerList({ page: this.searchForm.page, size: size, key: this.searchForm.key })
      },
      // 保存为动态群组
      handleSaveAsSmart () {
        if (!this.smartGroup) {
          this.$message({
            type: 'info',
            message: '请输入群组名！'
          })
          return false
        }
        this.isSaving = true
        let queryPara = {
          key: this.searchForm.key,
          labelId: this.labelId
        }
        if (this.selCondition) {
          this.createDynamicGroup2({groupName: this.smartGroup, queryPara: queryPara})
          .then((res) => {
            if (res.data.code === 1) {
              this.dialogVisible1 = false
              this.$message({
                type: 'success',
                message: res.data.msgZ
              })
            } else {
              this.$message({
                type: 'info',
                message: res.data.msgZ
              })
            }
            this.isSaving = false
          })
        } else {
          this.$message({
            type: 'info',
            message: '请选择标签分类!'
          })
          this.isSaving = false
        }
      },
      // 保存为静态群组弹层
      handleAddStatic (type) {
        if (type === '2') {
          if (this.selections.length > 0) {
            this.dialogVisible3 = true
            this.addStaticType = type
          } else {
            this.$message({
              type: 'info',
              message: '请选择群组!'
            })
          }
        } else {
          this.dialogVisible3 = true
          this.addStaticType = type
        }
      },
      // 保存为新静态群组
      handleSaveAsNewStatic () {
        this.isSaving = true
        if (this.addStaticType === '2') {
          let groupName = this.staticGroup
          let ids = []
          for (var i = 0; i < this.selections.length; i++) {
            ids.push(this.selections[i].id)
          }
          this.createStaticGroup3({groupName, ids})
            .then((res) => {
              this.isSaving = false
              this.dialogVisible3 = false
              if (res.data.code === 1) {
                this.getCustomerList({ ...this.searchForm })
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                })
              }
            })
        } else if (this.addStaticType === '1') {
          let groupName = this.staticGroup
          let queryPara = {
            key: this.searchForm.key
          }
          this.createStaticGroup3({groupName, queryPara})
            .then((res) => {
              this.isSaving = false
              this.dialogVisible3 = false
              if (res.data.code === 1) {
                this.getCustomerList({ ...this.searchForm })
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                })
              }
            })
        }
        this.staticGroup2 = ''
      },
      // 保存为已存在静态群组
      async handleSaveAsExistStatic () {
        this.isSaving = true
        if (!this.staticGroup2) {
          this.$message({
            type: 'info',
            message: '请输入群组名！'
          })
          this.isSaving = false
          return false
        }
        const ids = this.selections.map(item => {
          return item.id
        })
        const groupId = this.staticGroup2
        const res = await this.addToStaticGroup3({groupId, ids})
        if (res.data.code === 1) {
          this.$message.success(res.data.msgZ)
          this.isSaving = false
          this.dialogVisible3 = false
        } else {
          this.$message({
            type: 'info',
            message: res.data.msgZ
          })
        }
      },
      // 获取用户标签
      customerTagsString (tags) {
        if (tags) {
          return tags.map(item => {
            return item.name
          }).join(',')
        }
      },
      // 删除标签
      handleCloseTag (scope, tag) {
        scope.row.tags.splice(scope.row.tags.indexOf(tag), 1)
      },
      // 搜索群组
      handleSearchGroup (query) {
        if (query) {
          this.groupLoading = true
          this.getCusGroups2({wd: query, status: 1, type: 2, size: 10, page: 1, customerType: 2})
            .then(() => {
              this.groupLoading = false
            })
        }
      },
      // 搜索标签
      queryTagAsync (queryString) {
        let wd = queryString
        let gid = this.groupId
        let page = 1
        let size = 10
        this.searchTags({wd, gid, page, size})
      },
      // 添加标签弹层
      handleAddTag (type) {
        if (type === '2') {
          if (this.selections.length > 0) {
            this.addTagType = type
            this.dialogVisible2 = true
          } else {
            this.$message({
              type: 'info',
              message: '请选择群组!'
            })
          }
        } else {
          this.addTagType = type
          this.dialogVisible2 = true
        }
      },
      // 添加标签保存
      handleSaveTag () {
        this.isSaving = true
        if (this.addTagType === '2') {
          let buyerIds = this.selections.map(item => {
            return item.id
          })
          let tagId = this.tagID
          this.addCusTagByID({tagId, buyerIds})
            .then(res => {
              this.isSaving = false
              this.dialogVisible2 = false
              if (res.data.code === 1) {
                this.getCustomerList({ ...this.searchForm })
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                })
              }
            })
        } else if (this.addTagType === '1') {
          let tagId = this.tagID
          let conditionBuyer = {
            key: this.searchForm.key
          }
          this.addCusTagByCondition({tagId, conditionBuyer: conditionBuyer})
            .then(res => {
              this.isSaving = false
              this.dialogVisible2 = false
              if (res.data.code === 1) {
                this.getCustomerList({ ...this.searchForm })
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                })
              }
            })
        }
      },
      // 查询营销次数
      handleOpenDialog (scope) {
        this.dialogVisible4 = true
        this.dialogData = this.$_.cloneDeep(scope.row)
        this.handleSearchCount()
      },
      handleSearchCount () {
        this.getSaleRecord({
          page: this.dialogPage,
          size: this.dialogSize,
          mobile: this.dialogData.mobile,
          email: this.dialogData.email
        }).then((res) => {
          this.broadData = res.data.data
        })
      },
      // 改变弹框分页大小
      handleDialogSizeChange (size) {
        this.dialogSize = size
        this.getSaleRecord({
          page: this.dialogPage,
          size: this.dialogSize,
          mobile: this.dialogData.mobile,
          email: this.dialogData.email
        }).then((res) => {
          this.broadData = res.data.data
        })
      },
      // 弹窗数据排序
      handleSortChange (order) {
        console.log(order)
      }
    }
  }
</script>

<style lang="scss">
  .el-input-group__append .el-button{
    color: #333 !important;
  }
  .custList{
    .m-select{
      p{
        float: left;
        margin-right: 26px;
        color: #333;
      }
      margin: 8px 0 0 0;
    }
    .el-form-item{
      margin-bottom: 10px;
    }
    .table-wrap{
      margin: 15px 0;
    }
    .upload-wrap{
      display: inline-block;
    }
    .btn-primary{
      text-decoration: none;
      font-size: 14px;
      color: rgb(31, 45, 61);
      height: 34px;
      line-height: 34px;
      display: inline-block;
      padding: 0 5px;
    }
    .btn-primary:hover{
      color: #20a0ff;
      border-color: #20a0ff;
    }
    .el-row{margin-bottom: 10px;}
    .el-select{margin-right: 5px;}
    .cell a{color:#20a0ff;text-decoration: none;}
    .cell a:hover{color:#ff0000;}
    .dialog-footer{border: none;}
    .import-result{
      .sp{line-height: 30px;padding: 0 10px 10px 0;}
    }
  }
</style>
